/*************************************************************************
	> File Name: cancel_disable.c
	> Author: 
	> Mail: 
	> Created Time: 2015年01月14日 星期三 16时34分17秒
 ************************************************************************/

#include <pthread.h>
#include "errors.h"

static int counter;

void * thread_routine(void * arg){
    int state;
    int status;

    for(counter = 0;;counter++){
        // 775 iterations ,disable cancellation and sleep one second 
        // don't use function like printf .it will became a cancel point
        // and influence the result
        if((counter % 755 ) == 0){

            status = pthread_setcancelstate(PTHREAD_CANCEL_DISABLE,&state);
            if(status) err_abort(status,"disable cancel");

            sleep(1);

            status = pthread_setcancelstate(state,&state);
            if(status) err_abort(status,"Restore cancel");
        }
        if((counter % 1000) == 0){
            pthread_testcancel();
        }
        
    }
}

int main(int argc , char *argv[]){
    pthread_t thread_id;
    void *result;
    int status;


    status = pthread_create(&thread_id,NULL,thread_routine,NULL);
    if(status)  err_abort(status,"Created thread ");

    sleep(2);

    printf("calling cancel \n");

    status = pthread_cancel(thread_id);
    if(status)  err_abort(status,"Cancel thread ");

    printf("calling join\n");

    status = pthread_join(thread_id,&result);
    if(status) err_abort(status, "Join thread");

    if(result == PTHREAD_CANCELED)
        printf("Thread canceled at iteration %d\n",counter);
    else
        printf("Thread is not canceled\n");

    return 0;
}

